package com.xxadmin.usercenter.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xxadmin.common.dto.PageInfoDTO;
import com.xxadmin.common.exception.BusinessException;
import com.xxadmin.common.util.clone.CopyUtils;
import com.xxadmin.common.util.page.PageUtils;
import com.xxadmin.usercenter.dao.RoleDetailDao;
import com.xxadmin.usercenter.domain.RoleDetail;
import com.xxadmin.usercenter.dto.RoleDetailDTO;
import com.xxadmin.usercenter.dto.RoleDetailQueryDTO;
import com.xxadmin.usercenter.service.RoleDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 角色实现类
 *
 * @author:chenming
 * @date:2018/9/3
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)
public class RoleDetailServiceImpl implements RoleDetailService{

    @Autowired
    private RoleDetailDao roleDetailDao;

    @Override
    public void addRoleDetail(RoleDetailDTO roleDetailDTO) {

        if(roleIsExist(roleDetailDTO.getRoleName(),roleDetailDTO.getChannelCode())){
            throw new BusinessException("000201","该渠道下已经存在该角色了，请勿重复添加");
        }

        RoleDetail roleDetail = CopyUtils.copyBean(roleDetailDTO,RoleDetail.class);

        roleDetail.setCreateTime(new Date());

        roleDetailDao.insertSelective(roleDetail);
    }

    private boolean roleIsExist(String roleName, String channelCode) {
        RoleDetail roleDetail = roleDetailDao.selectRoleDetailByNameAndChannelCode(roleName,channelCode);

        return roleDetail != null;
    }

    @Override
    public void updateRoleDetail(RoleDetailDTO roleDetailDTO) {
        RoleDetail roleDetail = CopyUtils.copyBean(roleDetailDTO,RoleDetail.class);

        roleDetail.setUpdateTime(new Date());

        roleDetailDao.updateByPrimaryKeySelective(roleDetail);
    }

    @Override
    public RoleDetailDTO getRoleDetail(Integer id) {
        RoleDetail roleDetail = roleDetailDao.selectByPrimaryKey(id);

        return CopyUtils.copyBean(roleDetail,RoleDetailDTO.class);
    }

    @Override
    public PageInfoDTO<RoleDetailDTO> listRoleDetail(RoleDetailQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPageNum(),queryDTO.getPageSize());

        Page<RoleDetail> page = roleDetailDao.selectRoleDetail(queryDTO);

        return PageUtils.getPageInfoDTO(page,RoleDetailDTO.class);
    }
}
